import React, { PureComponent, Fragment } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import {
    Form,
    Input,
    Radio,
    InputNumber,
    TreeSelect,
    Select,
    DatePicker,
    Tree,
    Checkbox,
    Row,
    Col,
    Divider
} from 'antd';
import Neditor from "../Neditor"
import Ueditor from "../Ueditor"
import * as Tip from "../Msgbox";
import CheckInput from "../CheckInput";
import ColorPicker from "../ColorPicker";
import './index.less'
import { Upload } from '../index';
import { Conf, Luck, ajax } from '../../utils';
import { axiosConfig } from '../../utils/ajax/config';

class Index extends PureComponent{
    render(){
        const { style, layout, data } = this.props;

        return (
            <div className="searchtool" style={style}>
                <Form
                    layout={layout}
                    onSubmit={this.handleSearch}
                    >
                    {
                        data?data.map((item,index)=>{
                            return <Fragment key={index}>{ this.itemlist(item) }</Fragment>
                        }):''
                    }
                    {this.props.children}
                </Form>
            </div>
        )
    }

    getItemsValue = async ()=>{    //3、自定义方法，用来传递数据（需要在父组件中调用获取数据）
        //const valus= this.props.form.getFieldsValue();       //4、getFieldsValue：获取一组输入控件的值，如不传入参数，则获取全部组件的值
        let values = await this.checkValues();
        return values;
    }
    //设置值
    setItemsValue = (name,value)=>{
        this.props.form.setFieldsValue({[name]:value});
    }
    //重置
    handleReset = () => {
        this.props.form.resetFields();
    }
    checkValues = ()=>{
        return new Promise((resolve,reject)=>{
            let newvalue={};
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    Object.keys(values).forEach(function(key){
                        if(values[key]){
                            newvalue[key]=values[key];
                        }
                   });
                    resolve(newvalue);
                }else{
                    //reject('验证失败');
                    resolve(false);
                }
            });
        })
    }

    // handleButton = (e) => {
    //     e.preventDefault();
    //     this.props.form.validateFields((err, values) => {
    //         if (!err) {
    //             console.log('Received values of form: ', values);
    //         }
    //     });
    // }

    
    itemlist=(data)=>{
        const { layout } = this.props;

        const formItemLayout = layout === 'horizontal' ? {
            labelCol: { span: 6 },
            wrapperCol: { span: 17 },
        } : null;
        const { getFieldDecorator } = this.props.form;

        switch (data['type']) {
            case 'radio':
                return(<Fragment>
                    <Form.Item
                        label={data['title']}
                        {...formItemLayout}
                    >
                        {getFieldDecorator(`${data['name']}`,{
                            rules : data['rules'],
                            initialValue : data.hasOwnProperty('value') ? data['value'] : data['options'][0]['value']
                        })(
                            <Radio.Group onChange={data['onChange']}>
                                { data['options'].map((item,index)=>{
                                    return <Radio value={item.value} key={index}>{item.name}</Radio>
                                }) }
                            </Radio.Group>
                        )}
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'radio.button':
                return(<Fragment>
                    <Form.Item
                        label={data['title']}
                        {...formItemLayout}
                    >
                        {getFieldDecorator(`${data['name']}`,{
                            rules : data['rules'],
                            initialValue : data.hasOwnProperty('value') ? data['value'] : data['options'][0]['value']
                        })(
                            <Radio.Group onChange={data['onChange']}>
                                { data['options'].map((item,index)=>{
                                    return <Radio.Button value={item.value} key={index}>{item.name}</Radio.Button>
                                }) }
                            </Radio.Group>
                        )}
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'checkbox.line':
                return(<Fragment>
					<Form.Item
						label={data['title']}
						{...formItemLayout}
					>
						{getFieldDecorator(`${data['name']}`,{
							rules : data['rules'],
							initialValue : data['value']
						})(
							<Checkbox.Group onChange={data['onChange']}>
								{ data['options'].map((item,index)=>{
									return (
										<Checkbox key={index} value={item.value}>{item.name}</Checkbox>
									)
								}) }
							</Checkbox.Group>
						)}
                    </Form.Item>
                    {data['line']?<Divider />:""}
				</Fragment>);
			case 'checkbox':
                return(<Fragment>
					<Form.Item
						label={data['title']}
						formItemLayout="vertical"
					>
						{getFieldDecorator(`${data['name']}`,{
							rules : data['rules'],
							initialValue : data['value']
						})(
							<Checkbox.Group onChange={data['onChange']}>
								<Row>
								{ data['options'].map((item,index)=>{
									return (<Col span={8} key={index}>
										<Checkbox value={item.value}>{item.name}</Checkbox>
									</Col>)
								}) }
								</Row>
							</Checkbox.Group>
						)}
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'input.checked':
                return(<Fragment>
                    <Form.Item
                        label={data['title']}
                        {...formItemLayout}
                    >
                        <CheckInput
                            form={this.props.form}
                            data = {data}
                            placeholder={data['placeholder']}
                            autoFocus={data['autoFocus']}
                            //onChange = {this.checkedChange.bind(this,data)}
                            oninputChange = {this.oninputChange.bind(this,data)}
                        />
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'input':
                return(<Fragment>
                    <Form.Item
                        label={data['title']}
                        {...formItemLayout}
                    >
                        {getFieldDecorator(`${data['name']}`,{
                            rules : data['rules'],
                            initialValue : data['value']
                        })(
                            <Input placeholder={data['placeholder']} style={data['style']} autoComplete="off" autoFocus={data['autoFocus']?data['autoFocus']:false} disabled={data['disabled']?data['disabled']:false} size={data['size']} />
                        )}
                        {data['tip']?<div>{data['tip']}</div>:""}
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'input.color':
                return(<Fragment><Form.Item
                    label={data['title']}
                    {...formItemLayout}
                >
                    {getFieldDecorator(`${data['name']}`,{
                        rules : data['rules'],
                        initialValue : data['value']
                    })(
                        <ColorPicker data={data} onClick={this.colorClick.bind(this,data)} setColor={this.setColor.bind(this,data)} />
                    )}
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'input.pass':
                return(<Fragment><Form.Item
                    label={data['title']}
                    {...formItemLayout}
                >
                    {getFieldDecorator(`${data['name']}`,{
                        rules : data['rules'],
                        initialValue : data['value']
                    })(
                        <Input.Password placeholder={data['placeholder']} size={data['size']} style={data['style']} />
                    )}
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'input.number':
                return(<Fragment><Form.Item
                    label={data['title']}
                    {...formItemLayout}
                >
                    {getFieldDecorator(`${data['name']}`,{
                        rules : data['rules'],
                        initialValue : data['value']
                    })(
                        <InputNumber min={data['min']} max={data['max']} placeholder={data['placeholder']} size={data['size']} style={data['style']} />
                    )}
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
                
            case 'input.month':
                return(<Fragment>
                    <Form.Item
                        label={data['title']}
                        {...formItemLayout}
                    >
                        {getFieldDecorator(`${data['name']}`,{
                            rules : data['rules'],
                            initialValue : Luck.tamptotime(data['value'],'m')
                        })(
                            <div style={{display:'none'}}>
                                <Input placeholder={data['placeholder']} size={data['size']} />
                            </div>
                        )}
                        <DatePicker placeholder={data['placeholder']} onChange={this.changeDate.bind(this,data)} defaultValue={data['value']>0?moment(Luck.tamptotime(data['value'],'m')):moment()} />
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'input.time':
                return(<Fragment>
                    <Form.Item
                        label={data['title']}
                        {...formItemLayout}
                    >
                        {getFieldDecorator(`${data['name']}`,{
                            rules : data['rules'],
                            initialValue : data['value']>0?Luck.tamptotime(data['value']):""
                        })(
                            <div style={{display:'none'}}>
                            <Input placeholder={data['placeholder']} size={data['size']} />
                            </div>
                        )}
                        <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder={data['placeholder']} onChange={this.changeDate.bind(this,data)} defaultValue={data['value']>0?moment(Luck.tamptotime(data['value'])):moment()} />
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);

            case 'input.hidden':
                return(<div style={{display:'none'}}>
                    <Form.Item
                        label={data['title']}
                        {...formItemLayout}
                    >
                        {getFieldDecorator(`${data['name']}`,{
                            rules : data['rules'],
                            initialValue : data['value']
                        })(
                            <Input placeholder={data['placeholder']} disabled={data['disabled']} size={data['size']} />
                        )}
                    </Form.Item>  
                </div>);
            case 'select.tree':
                return(<Fragment><Form.Item
                    label={data['title']}
                    {...formItemLayout}
                >
                    {getFieldDecorator(`${data['name']}`,{
                        rules : data['rules'],
                        initialValue : data['value']
                    })(
                        // <Input placeholder={data['placeholder']} disabled={data['disabled']} />
                        <TreeSelect
                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                            treeData={data['treeData']}
                            placeholder={data['placeholder']}
                            treeDefaultExpandAll={true}
                            treeCheckable = {false}
                            size={data['size']}
                        />
                    )}
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'select.treeopen':
                return(<Fragment><Form.Item
                    label={data['title']}
                    {...formItemLayout}
                >
                    {getFieldDecorator(`${data['name']}`,{
                        rules : data['rules'],
                        initialValue : data['value']
                    })(
                        // <Input placeholder={data['placeholder']} disabled={data['disabled']} />
                        <TreeSelect
                            dropdownStyle={{ minHeight: 400, overflow: 'auto' }}
                            treeData={data['treeData']}
                            placeholder={data['placeholder']}
                            treeDefaultExpandAll={true}
                            treeCheckable = {false}
                            size={data['size']}
                        />
                    )}
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'input.treeselect':
                return(<Fragment><Form.Item
                    label={data['title']}
                    {...formItemLayout}
                >
                    {getFieldDecorator(`${data['name']}`,{
                        rules : data['rules'],
                        initialValue : data['value']
                    })(
                        <div style={{display:'none'}}>
                            <Input placeholder={data['placeholder']} size={data['size']} />
                        </div>
                    )}
                    {this.renderTree(data)}
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
                
            case 'input.treeselect.hide':
                return(<Fragment>
                    <Form.Item
                        label={data['title']}
                        {...formItemLayout}
                    >
                        {getFieldDecorator(`${data['name']}`,{
                            rules : data['rules'],
                            initialValue : data['value']
                        })(
                            <div style={{display:'none'}}>
                                <Input placeholder={data['placeholder']} size={data['size']} />
                            </div>
                        )}
                        {this.renderTreeChild(data)}
                    </Form.Item>
                    <div style={{display:'none'}}>
                        <Form.Item
                            label={data['title']}
                            {...formItemLayout}
                        >
                            {getFieldDecorator(`${data['childname']}`)(
                                <div style={{display:'none'}}>
                                    <Input placeholder={data['placeholder']} size={data['size']} />
                                </div>
                            )}
                        </Form.Item>
                    </div>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'upload':
                return(<Fragment><Form.Item
                    label={data['title']}
                    {...formItemLayout}
                >
                    {getFieldDecorator(`${data['name']}`,{
                        rules : data['rules'],
                        initialValue : data['value']
                    })(
                        <div style={{display:'none'}}>
                            <Input placeholder={data['placeholder']} size={data['size']} />
                        </div>
                    )}
                    { this.renderUpload(data,[]) }
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'text':
                return(<Fragment><Form.Item
                    label={data['title']}
                    {...formItemLayout}
                >
                    {getFieldDecorator(`${data['name']}`,{
                        rules : data['rules'],
                        initialValue : data['value']
                    })(
                        <Input.TextArea placeholder={data['placeholder']} rows={data['rows']} size={data['size']} />
                    )}
                    {data['tip']?<div>{data['tip']}</div>:""}
                    </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'text.editor':
                return(<Fragment><Form.Item
                    label={data['title']}
                    {...formItemLayout}
                >
                    {getFieldDecorator(`${data['name']}`,{
                        rules : data['rules'],
                        initialValue : data['value']
                    })(
                        // <BraftEditor
                        //     controls  = {data['controls']}
                        //     pasteMode = {['html']}
                        //     extendControls = {data['extendControls']}
                        //     onChange={this.handleEditorChange.bind(this,data)}
                        //     onSave={this.saveContent.bind(this,data)}
                        // />
                        <Neditor
                            content={data['value']}
                            handleChange={this.editorChange.bind(this,data)}
                            plugins={['insertLink','uploadImage','uploadVideo']}
                            uploadImage={this.uploadEditImage.bind(this,data)}
                            multipleImagesUpload={false}
                            progress={ data['progress'] }
                            config = { data['config'] }
                        />
                    )}
                </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'text.ueditor':
                return(<Fragment><Form.Item
                    label={data['title']}
                    {...formItemLayout}
                >
                    {getFieldDecorator(`${data['name']}`,{
                        rules : data['rules'],
                        initialValue : data['value']
                    })(
                        <Ueditor
                            id={data['value']}
                            content={data['value']}
                            config = { data['config'] }
                            handleChange={this.editorChange.bind(this,data)}
                        />
                    )}
                </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>);
            case 'select.icon':
                return(<Fragment><Form.Item
                    label={data['title']}
                    {...formItemLayout}
                >
                    {getFieldDecorator(`${data['name']}`,{
                        rules : data['rules'],
                        initialValue : data['value']
                    })(
                        <Select
                            showSearch
                            placeholder={data['placeholder']}
                            optionFilterProp="children"
                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                        >
                            {
                                ["lock","unlock","bars","book","calendar","cloud","cloud-download","code","copy","credit-card","delete","desktop","download","ellipsis","file","file-text","file-unknown","file-pdf","file-word","file-excel","file-jpg","file-ppt","file-markdown","file-add","folder","folder-open","folder-add","hdd","frown","meh","smile","inbox","laptop","appstore","link","mail","mobile","notification","paper-clip","picture","poweroff","reload","search","setting","share-alt","shopping-cart","tablet","tag","tags","to-top","upload","user","video-camera","home","loading","loading-3-quarters","cloud-upload","star","heart","environment","eye","eye-invisible","camera","save","team","solution","phone","filter","exception","export","customer-service","qrcode","scan","like","dislike","message","pay-circle","calculator","pushpin","bulb","select","switcher","rocket","bell","disconnect","database","compass","barcode","hourglass","key","flag","layout","printer","sound","usb","skin","tool","sync","wifi","car","schedule","user-add","user-delete","usergroup-add","usergroup-delete","man","woman","shop","gift","idcard","medicine-box","red-envelope","coffee","copyright","trademark","safety","wallet","bank","trophy","contacts","global","shake","api","fork","dashboard","table","profile","alert","audit","branches","build","border","crown","experiment","fire","money-collect","property-safety","read","reconciliation","rest","security-scan","insurance","interation","safety-certificate","project","thunderbolt","block","cluster","deployment-unit","dollar","euro","pound","file-done","file-exclamation","file-protect","file-search","file-sync","gateway","gold","robot","shopping","import","export"]
                                .map((item,index)=>{
                                    return <Select.Option key={index} value={item}>{item}</Select.Option>
                                })
                            }
                        </Select>
                    )}
                </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>)
            
            case 'select':
                return(<Fragment><Form.Item
                    label={data['title']}
                    {...formItemLayout}
                >
                    {getFieldDecorator(`${data['name']}`,{
                        rules : data['rules'],
                        initialValue : data.hasOwnProperty('value') ? data['value'] : data['options'][0]['value']
                    })(
                        <Select
                            showSearch
                            placeholder={data['placeholder']}
                            onChange={data['onChange']}
                        >
                            {
                                data['options'].map((item,index)=>{
                                    return <Select.Option key={index} value={item['value']}>{item['name']}</Select.Option>
                                })
                            }
                        </Select>
                    )}
                </Form.Item>
                    {data['line']?<Divider />:""}
                </Fragment>)
            default:
                break;
        }
    }
    //颜色点击
    colorClick = (data,e)=>{
        console.log(data,e);
    }
    setColor = (data,v)=>{
        this.setItemsValue(data['name'],v);
    }
    //多选绑定input
    // checkedChange = (data,e)=>{
    //     console.log(e);
    // }
    oninputChange = (data,v)=>{
        this.setItemsValue(data['name'],v);
    }

    uploadEditImage = async (data,e)=>{
        let files = e.target.files;
        let url = axiosConfig.baseURL+'upload';
        let images = [];
        for(let i=0;i<files.length;i++){
            let formData = new FormData();
            formData.append('file',files.item(i));
            formData.append('path',data['path']);
            formData.append('type','photo');
            formData.append('size',6);
            if(this.checkUpload(files.item(i),6,"photo")){
                let one = await ajax.upload(url,formData,'post',false);
                if(one.code === 0){
                    images.push(Conf.fileUrl+one.url);
                }else{
                    Tip.Message(one.msg,'error');
                }
            }
        }
        //console.log(images)
        return images;
        /*return new Promise((resolve, reject)=>{
            resolve(images[0])
        })*/
    }

    uploadVideo = async (data,e)=>{
        let files = e.target.files;
        let url = axiosConfig.baseURL+'upload';
        let videos = [];
        for(let i=0;i<files.length;i++){
            let formData = new FormData();
            formData.append('file',files.item(i));
            formData.append('path',data['path']+"_video");
            formData.append('type','video');
            formData.append('size',1000);
            if(this.checkUpload(files.item(i),1000,"video")){
                let one = await ajax.upload(url,formData,'post',false);
                if(one.code === 0){
                    videos.push(Conf.fileUrl+one.url);
                }else{
                    Tip.Message(one.msg,'error');
                }
            }
        }
        return videos;
    }

    checkUpload = (file,size,type)=>{
        const isJPG = type === 'photo'?file.type.indexOf("image/") !== -1:file.type.indexOf("video/")!== -1;
        if (!isJPG) {
            if(type === 'photo'){
                Tip.Message('只能上传图片类型!','error');
            }else{
                Tip.Message('只能上传视频类型!','error');
            }
        }
        const isLt4M = file.size / 1024 / 1024 < size;
        if (!isLt4M) {
            Tip.Message('上传大小不能超过'+size+'MB!','error');
        }

        return isJPG && isLt4M;
    }

    editorChange = (data,v)=>{
        this.setItemsValue(data['name'],v);
    }

    changeDate=(data,e,v)=>{
        this.setItemsValue(data['name'],v);
    }

    renderUpload = (data,fileList)=>{
        if(fileList.length === 0){
            //判断是否有默认值
            let filevalue=data['value'];
            if(filevalue){
                if(typeof(filevalue) === 'string'){
                    let fileobj={
                        url:Conf.fileUrl + filevalue,
                        uid:1,
                        name: data['name'],
                        status: 'done'
                    }
                    fileList.push(fileobj);
                }else{
                    for (let i = 0; i < filevalue.length; i++) {
                        let fileobj={
                            url:Conf.fileUrl + filevalue[i],
                            uid: i+1,
                            name: data['name']+i,
                            status: 'done'
                        };
                        fileList.push(fileobj);
                    }
                }
            }else{
                fileList=[];
            }
        }
        let dada = data['data'] ? data['data'] : {};
        //let path = dada['path'] ? dada['path'] : 'default';
        let accept = dada['accept'] ? dada['accept'] : 'photo';
        dada['size'] = dada['size'] ? dada['size'] : 4;

        data.listType = data.listType ? data.listType : "picture-card";
        return(
            <Upload
                //path={path}
                length = {data['length']}
                fileList={fileList}
                accept = {accept}
                data = {dada}
                setValue = { this.setItemsValue }
                fieldname={ data['name'] }
                fieldvalue={ data['value'] }
            />
        )
    }
    
    //renderTreeNode
    renderTree = (data,bool=false)=>{
        let keys=[];
        if(data["value"]!==""){
            keys=data["value"].split(',');
        }
        return(
            <Tree
                checkable={true}
                onCheck={this.treeCheck.bind(this,data["name"])}
                defaultCheckedKeys={keys}
                defaultExpandAll={bool}
            >
                {this.renderTreeNode(data['data'])}
            </Tree>
        )
    }
    renderTreeNode = (data)=>{
        return data.map((item)=>{
            if(item.children===undefined || item.children===[] || item.children==null || item.children==="" || item.children.length<1){
                return (
                    <Tree.TreeNode
                        key={item.key}
                        title={item.title}
                        selectable={false}
                    />
                );
            }else{
                return(
                    <Tree.TreeNode 
                        key={item.key}
                        title={item.title}
                        selectable={false}
                    >
                        {this.renderTreeNode(item.children)}
                    </Tree.TreeNode>
                )
            }
        })
    }

    renderTreeChild = (data,bool=true)=>{
        let keys=[];
        if(data["value"]!==""){
            keys=data["value"].split(',');
        }
        return(
            <Tree
                checkable={true}
                onCheck={this.treeCheckChild.bind(this,data)}
                defaultCheckedKeys={keys}
                defaultExpandAll={bool}
            >
                {this.renderTreeNode(data['data'])}
            </Tree>
        )
    }

    treeCheck = (name,checkKeys,e)=>{
        let keys = [...checkKeys,...e.halfCheckedKeys];
        let value = " ";
        if(keys.length!==0){
            value = keys.join(",");
        }
        this.setItemsValue(name,value);
    }
    treeCheckChild = (data,checkKeys,e)=>{
        let keys = [...checkKeys,...e.halfCheckedKeys];
        let value = " ";
        if(keys.length!==0){
            value = keys.join(",");
        }
        let value2 = " ";
        if(checkKeys.length!==0){
            value2 = checkKeys.join(",");
        }
        this.setItemsValue(data['name'],value);
        this.setItemsValue(data['childname'],value2);
    }
    
}

Index.propTypes = {
    data:PropTypes.array.isRequired
}

/**
 * @param data
 * @param style={{ marginBottom: 16 }}
 * @param layout = 'inline'
 * @param hidedata
 * @param const data = [
        {
            type:'radio',
            title:'状态',
            name:'status',
            value:[
                {value:1,name:'启动'},
                {value:2,name:'禁用'}
            ],
            rules:[{
                required: true,
                message: '错误'
            }]
        },
        {
            type:'input',
            title:'姓名',
            name:'name',
            value:'',
            placeholder:"请输入提示",
            rules:[{
                required: true,
                message: '错误'
            }]
        }
    ]
    const hidedata = [
        {
            type:'input',
            title:'密码',
            name:'password',
            value:'',
            placeholder:"请输入提示"
        }
    ]
@param {type:'upload',title:'头像',name:'nickname2',value:'/uploads/avater/20190116/20190116143636717155.jpg',length:1,data:{type:'xx',size:6,path:'avater',accept:'*'}}
 */
const IndexForm=Form.create({ name: 'form' })(Index)

// class Index extends PureComponent{
//     render(){
//         const { data, style, layout } = this.props;
//         return(
//             <WapperForm data={data} style={style} layout={layout} />
//         )
//     }
// }


export default IndexForm;